console.log('background.js')
importScripts('config.js');

//监听content通讯
chrome.runtime.onMessage.addListener((request, sender, callback) => {
    backEvent[request.action](request.data, callback, sender);
    return true
});

//监听页面卡住后自动刷新[每隔20s检测一次，60s前台没有请求就当页面被卡住了]
var lastTime = null
function setLastTime() {
    lastTime = Math.round(new Date() / 1000)
}
function checkReload() {
    let currentTime = Math.round(new Date() / 1000)
    if (!lastTime) {
        setLastTime()
    }
    if (currentTime-lastTime>=60) {
        console.log('checkReload')
        return true
    }
    return false
}
async function getTabs() {
    let list = await chrome.tabs.query({});
    return list;
}
setInterval(() => {
    if (checkReload()) {
        getTabs().then(list=>{
            list.reverse()
            for(let i in list) {
                if ((/aiscore\.com/i).test(list[i].url)) {
                    setLastTime()
                    tabId = list[i].id
                    chrome.tabs.reload(tabId)
                    break
                }
            }
        })
    }
}, 20000);

//background方法封装
var backEvent = {
    //批量插入数据
    insertData: (data, callback)=> {
        setLastTime();
        // console.log(data)

        //新接口，防止和php-es框架a参数冲突，整体套个params参数
        let bodyParams = {params: data};
        ajax("https://ball.wbball.com/api/match_recent/match_odds", bodyParams, (res) => {
            callback(res);
        });

        //老接口
        // ajax("https://sports.wbball.com/api/match_odds", data, (res) => {
        //     callback(res);
        // });
    },
    //清除缓存
    cleanCache: (data, callback)=>{
        var millisecondsPerHour = 1000 * 60 * 60;
        var oneHourAgo = (new Date()).getTime() - millisecondsPerHour;
        chrome.browsingData.remove({
            "since": oneHourAgo
        }, {
            "appcache": true,
            "cache": true,
            "cacheStorage": true,
            "cookies": true,
            "downloads": true,
            "fileSystems": true,
            "formData": true,
            "history": true,
            "indexedDB": true,
            "localStorage": true,
            "passwords": true,
            "serviceWorkers": true,
            "webSQL": true
        }, ()=>{
            callback({msg:"清缓存成功"})
        });
    }
}